import { Inject, Injectable } from '@nestjs/common';
import { CreateDemoDto } from './dto/create-demo.dto';
import { PrismaService } from '../common/prisma/prisma.service';
import { ResultCodeEnum } from '@/common/enums/resultCode.enum';
import { RedisService } from '@/common/redis/redis.service';
import { LoggerService } from '@/common/logger/logger.service';
import { handleError } from '@/utils/handle.error';
import { Cacheable, CacheEvict } from '@/common/decorators/cache.decorator';
import { RedisKeyEnum } from '@/common/enums/redis-key.enum';

@Injectable()
export class DemoService {
  @Inject(PrismaService)
  private prisma: PrismaService;

  @Inject(RedisService)
  private redisService: RedisService;

  @Inject(LoggerService)
  private logger: LoggerService;

  async create(createDemoDto: CreateDemoDto) {
    const findOne = await this.prisma.user.findFirst({
      where: {
        name: createDemoDto.name,
      },
    });
    if (findOne) {
      handleError(this.logger, 111, {
        common: '创建失败',
      })
      return '名称重复';
      // {
      //   msg: '名称重复',
      //   data: null,
      // };
    }
    try {
      const { id } = await this.prisma.user.create({
        data: createDemoDto,
        select: {
          id: true,
        },
      });
      return {
        msg: '创建成功',
        data: id,
      };
    } catch (error) {
      handleError(this.logger, error, {
        common: '创建失败',
      })
      // return {
      //   msg: '创建失败',
      //   data: error,
      // };
    }
  }

  @CacheEvict(RedisKeyEnum.DemoKey)
  findAll() {
    return `This action returns all demo`;
  }

  @Cacheable(RedisKeyEnum.DemoKey)
  async findRedis(name: string) {
    console.log('打印***query', name);
    const demo = await this.prisma.user.findFirst({
      where: {
        name,
      },
    });
    console.log('打印***demo', demo);
    return {
      code: ResultCodeEnum.SUCCESS,
      data: demo,
      message: '查询成功',
    };
  }

  @Cacheable(RedisKeyEnum.DemoKey)
  async findRedis2(name: string) {
    const demo = await this.prisma.user.findFirst({
      where: {
        name,
      },
    });
    return {
      code: ResultCodeEnum.SUCCESS,
      data: demo,
      message: '查询成功',
    };
  }


  async findOne(id: number, query: { name: string }) {
    console.log('打印***query', query);
    const demo = await this.prisma.user.findFirst({
      where: {
        name: query.name,
      },
    });
    return {
      code: ResultCodeEnum.ERROR,
      data: demo,
      message: '查询成功',
    };
  }

  // update(id: number, updateDemoDto: UpdateDemoDto) {
  //   return `This action updates a #${id} demo`;
  // }

  remove(id: number) {
    return `This action removes a #${id} demo`;
  }
}
